/// 懒汉式单例，不存在线程安全问题
#include <functional>
#include <thread>
#include <vector>

template <typename T>
class Singleton {
public:
    static T& getInstance();
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    Singleton();
    ~Singleton();

    static T* instance_;
};

template <typename T>
T* Singleton<T>::instance_ = new T();

template <typename T>
T& Singleton<T>::getInstance()
{
    return *instance_;
}

/// test

struct MyStruct {
};

void getSingleton()
{
    MyStruct& ins = Singleton<MyStruct>::getInstance();
    printf("instance address: %p\n", &ins);
}

class MyClass {
public:
    MyClass(int x)
        : x_(x)
    {
    }

private:
    int x_;
};

int main(int argc, char* argv[])
{
    std::vector<std::thread> threads;
    for (int i = 0; i < 5; ++i) {
        threads.emplace_back(getSingleton);
    }
    for (auto &t : threads) {
        t.join();
    }
    return 0;
}
